package com.onec.service.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 *
 */
public class ThreadPoolUtil {


  /**
   * 创建一个新的线程
   */
  public static void createThread() {

    Thread thread = new Thread(() -> {
      System.out.println("ccccccc");
    });

    System.out.println(thread.getState());
    System.out.println(thread.getName());
    System.out.println(thread.getPriority());

    thread.start();
  }

  // 1，创建异步线程
  static class Thread1 extends Thread {

    @Override
    public void run() {
      // do something

    }

  }

  // 2 创建异步线程
  static class Thread2 implements Runnable {

    private Runnable runnable;

    public Thread2() {
    }

    public Thread2(Runnable runnable) {
      this.runnable = runnable;
    }

    @Override
    public void run() {
      // do something
      if (null != runnable) {
        runnable.run();
      }
    }
  }


  /**
   * 带有返回值的异步线程
   */
  static class RunnableTask implements Callable<Long> {

    @Override
    public Long call() throws Exception {
      return System.currentTimeMillis();
    }
  }


  public static void main(String[] args) throws ExecutionException, InterruptedException {
    Thread1 thread1 = new Thread1();
    thread1.start();

    //1
    Runnable runnable = new Thread2();
    Thread thread = new Thread(runnable);
    thread.start();

    //2 匿名内部类创建runnable
    Thread runnableThread = new Thread(new Runnable() {
      @Override
      public void run() {
        // do something

      }
    });
    runnableThread.start();

    // 3 lambda
    Thread lambda = new Thread(() -> {
      // do something
    });
    lambda.start();

    // 4 异步返回值
    RunnableTask runnableTask = new RunnableTask();
    FutureTask<Long> future = new FutureTask<Long>(runnableTask);
    Thread threadTask = new Thread(future, "返回值的task");
    threadTask.start();

    future.get();

    // 5，线程池 固定线程池 设置3
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    // 执行实例未返回
    executorService.execute(new Thread2());
    // 内部类
    executorService.execute(new Runnable() {
      @Override
      public void run() {

      }
    });

    // 5，具有返回的异步线程池
    Future<Long> result = executorService.submit(runnableTask);
    Long longResult = result.get();

    //

  }

  /**
   * A a = new thread();</br> main(){            </br> a.join();        </br> }
   * </br> a 线程继续执行       </br> main 线程 waiting 等待执行结果！
   */
  public static void join() {

  }

  /**
   * 放弃当前cpu 时间片 该线程处于就绪状态。
   */
  public static void yield() {
    Thread.yield();
  }

  /**
   *
   */
  public static void daemon() {
    Thread.yield();
  }


}
